package hu.issue.framework.web.tag;

import java.io.IOException;

import hu.issue.framework.web.Constants;
import hu.issue.framework.web.validation.ErrorMessages;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

public class ErrorTag extends TagSupport {
	private static final long serialVersionUID = -4833176972887093687L;
	
	private String field;
	
	public void setField(String field) {
		this.field = field;
	}

	@Override
	public int doEndTag() throws JspException {
		ErrorMessages messages = (ErrorMessages)pageContext.getAttribute(Constants.FORM_ERROR, PageContext.REQUEST_SCOPE);
		if (messages == null) {
			return EVAL_PAGE;
		}
		
		String errorMessage = messages.getFieldMessage(field);		
		if (errorMessage == null) {
			return EVAL_PAGE;
		}
		
		try {
			JspWriter writer = pageContext.getOut();
			writer.append("<span class=\"error\">").append(errorMessage).append("</span>");
		} catch (IOException e) {
			throw new JspException(e);
		}
		
		return EVAL_PAGE;
	}
}
